<?php
// +----------------------------------------------------------------------
// | [RhaPHP System] Copyright (c) 2017 http://www.rhaphp.com/
// +----------------------------------------------------------------------
// | [RhaPHP] 并不是自由软件,你可免费使用,未经许可不能去掉RhaPHP相关版权
// +----------------------------------------------------------------------
// | Author: Geeson <qimengkeji@vip.qq.com>
// +----------------------------------------------------------------------


namespace app\admin\controller;

use think\exception\ErrorException;
use think\facade\Cache;
use think\Db;
use think\facade\Env;
use think\facade\Request;
use think\facade\Session;
use think\facade\Config;

class System extends Base
{

    public function initialize()
    {

        parent::initialize();

    }

    public function index()
    {
        $this->redirect('mp/index/mplist');
        return view();
    }

    public function menuList()
    {
        $allMenu = Db::name('menu')->order('sort ASC')->select();
        $menuList = \Tree::makeTree($allMenu);
        $this->assign('menuList', $menuList);

        return view('menulist');
    }

    public function addMenu()
    {
        if (Request::isPost()) {
            $_data = input('post.');
            unset($_data['mid']);
            if (Db::name('menu')->insert($_data)) {
                ajaxMsg(1, '增加成功');
            } else {
                ajaxMsg(0, '增加失败');
            }
        } else {
            $menu = Db::name('menu')->select();
            $tree = \Tree::makeTree($menu);
            $this->assign('menu_cate', $tree);
            return view('add_menu');
        }
    }

    public function delMenu($id)
    {
        if (Request::isAjax()) {
            Db::name('menu')->where(['id' => $id])->delete();
            ajaxMsg('1', '成功删除');
        }
    }

    public function deleteRole($id)
    {
        if (Request::isAjax()) {
            Db::name('admin_role')->where(['id' => $id])->delete();
            ajaxMsg('1', '成功删除');
        }
    }

    public function deleteAdmin($id)
    {
        if (Request::isAjax()) {
            if($this->admin_id !=$id ){
                Db::name('admin')->where(['id' => $id])->delete();
                ajaxMsg('1', '成功删除');
            }else{
                ajaxMsg('0', '不能删除自己');
            }

        }
    }


    public function updateMenu($id)
    {
        $this->assign('menu_title', '更改菜单');
        if (Request::isAjax()) {
            Db::name('menu')->where(['id' => $id])->update(input('post.'));
            ajaxMsg(1, '更新成功');

        } else {
            $meu = Db::name('menu')
                ->where(['id' => $id])->find();
            $menu = Db::name('menu')->select();
            $tree = \Tree::makeTree($menu);
            $this->assign('meu', $meu);
            $this->assign('menu_cate', $tree);
            return view('updatemenu');
        }
    }

    public function updateSort()
    {
        if (Request::isAjax()) {
            $_data = input();
            foreach ($_data as $key => $val) {
                if (!empty($_V = explode('_', $key))) {
                    Db::name('menu')->where(['id' => $_V[0]])->update(['sort' => $val]);
                }
            }
            ajaxMsg('1', '更新成功');
        }
    }

    public function AdminMember()
    {
        $admin = Db::name('admin')->select();
        $roleList = Db::name('admin_role')->select();
        $role =  array();
        foreach ($roleList as $item) {
            $role[$item['id']] = $item['role_name'];
        }
        foreach ($admin as $k=>$item) {

            $admin[$k]['role_name'] = isset($role[$item['role']]) ? $role[$item['role']] : '';
        }
        $this->assign('adminList', $admin);
        return view('adminmember');
    }

    public function addAdminMember()
    {
        if (Request::isAjax()) {
            $_data = input();
            if ($_data['password'] != $_data['repassword']) {
                ajaxMsg(0, '两次密码不匹配');
            }

//            $S = getAdmin();
//            if ($S['id'] != $this->admin_id) {
//                ajaxMsg('0', '你无权操作');
//            }
            if (!$result = Db::name('admin')->where('admin_name', 'eq', $_data['admin_name'])
                ->find()) {

                $rand_str = rand_string();
                $password = md5($_data['password'] . $rand_str);
                $data['admin_name'] = $_data['admin_name'];
                $data['role'] = $_data['role'];
                $data['password'] = $password;
                $data['rand_str'] = $rand_str;
                $data['admin_id'] = $this->admin_id;
                if (Db::name('admin')->insert($data)) {
                    ajaxMsg(1, '操作成功');
                } else {
                    ajaxMsg(0, '操作失败');
                }
            } else {
                ajaxMsg(0, '登录账户已经存在');
            }
        } else {
            $role_list = Db::name('admin_role')->select();
            $this->assign('role_list', $role_list);
            return view('addadminmember');
        }

    }

    public function disabledAdmin($id, $status = '')
    {
        if ($result = Db::name('admin')->where('id', 'eq', $id)->find()) {
            if ($result['id'] == 1) {
                ajaxMsg('0', '不能禁用超级管理员');
            }
//            if ($result['admin_id'] == $id) {
//                ajaxMsg('0', '不能禁用超级管理员');
//            }
//            if ($result['admin_id'] != $this->admin_id) {
//                ajaxMsg('0', '你无权操作');//禁用成员不属于当前管理员
//            }
//            if ($result['id'] != $this->admin_id) {
//                ajaxMsg('0', '你无权操作1');//禁用成员不属于当前管理员
//            }
        }
        if (Db::name('admin')->where(['id' => $id])->update(['status' => $status])) {
            Cache::rm('ststemAdmin');
            ajaxMsg(1, '操作成功');
        } else {
            ajaxMsg(0, '操作失败');
        }

    }

    public function updatePwd($id)
    {
        if (Request::isAjax()) {
            $_data = input();
            if ($_data['password'] != $_data['repassword']) {
                ajaxMsg(0, '两次密码不匹配');
            }
            if ($result = Db::name('admin')->where('id', 'eq', $id)

                ->find()) {
//                if ($result['admin_id'] != $this->admin_id) {
//                    ajaxMsg('0', '你无权操作');//禁用成员不属于当前管理员
//                }
//                $S_admin = getAdmin();
//                if ($S_admin['id'] != $this->admin_id) {//不是超级管理员
//                    if ($id != $S_admin['id']) {
//                        ajaxMsg('0', '只能超级管理员更改其它成员密码');
//                    }
//                }
                $rand_str = rand_string();
                $password = md5($_data['password'] . $rand_str);
                if (Db::name('admin')->where(['id' => $id])->update(['password' => $password, 'rand_str' => $rand_str])) {
                    ajaxMsg(1, '操作成功');
                } else {
                    ajaxMsg(0, '操作失败');
                }

            } else {
                ajaxMsg(0, '没有此成员');
            }
        } else {

            return view('updatepwd');
        }
    }

    public function updatePower($id)
    {
        if (Request::isAjax()) {
            $_data = input();
            if ($result = Db::name('admin')->where('id', 'eq', $id)

                ->find()) {

                $role_id = $_data['role'] > 0 ? $_data['role'] : 0;

               Db::name('admin')->where(['id' => $id])->update(['role' => $role_id]);
                    Cache::clear();
                    ajaxMsg(1, '操作成功');


            } else {
                ajaxMsg(0, '没有此成员');
            }
        } else {
            $role_list = Db::name('admin_role')->select();
            $admin = Db::name('admin')->where(['id' => $id])->find();
            $this->assign('role_list', $role_list);
            $this->assign('admin', $admin);
            return view('updatepower');
        }
    }

    public function cacheClear()
    {
        Cache::clear();
        $path = Env::get('runtime_path');
        if ($this->delDirAndFile($path) == false) {
            ajaxMsg(0, '清空缓存失败，请检查runtime目录是否有删除权限。');
        } else {
            ajaxMsg(1, '清空缓存成功');
        }

    }

    private function delDirAndFile($path, $delDir = FALSE)
    {
        $handle = opendir($path);
        if ($handle) {
            while (false !== ($item = readdir($handle))) {
                if ($item != '.' && $item != '..')
                    is_dir($path.DS.$item) ? $this->delDirAndFile($path.DS.$item, $delDir) : unlink($path.DS.$item);
            }
            closedir($handle);
            if ($delDir)
                return rmdir($path);
        } else {
            if (file_exists($path)) {
                return unlink($path);
            }
        }
        return true;
    }


    public function mysqlAction(){
        $recordList = Db::name('back_record')->order('create_time DESC')->paginate(20);
        $page = $recordList->render();
        $adminList = Db::name('admin')->select();
        $admin_name = array();
        foreach ($adminList as $item) {
            $admin_name[$item['id']] = $item['admin_name'];
        }
        $list = array();
        foreach ($recordList as $item) {
            $item['create_time'] = date('Y-m-d H:i',$item['create_time']);
            $item['admin_name'] = isset($admin_name[$item['admin_id']])? $admin_name[$item['admin_id']] : "";
            $list[] = $item;
        }
        $this->assign('list', $list);
        $this->assign('page', $page);
        return view();

    }

    function deleteBackRecord($id=''){
        Db::name('back_record')->where(['id' => $id])->delete();
    }
    public function backupSql(){
        header("Content-type:text/html;charset=utf-8");
        $date = date('YmdHis');
        $database = Config::get('database.database');

        $path =  ROOT_PATH .'/'. ENTR_PATH . '/uploads/backup/'.$database.'/';

        if (!file_exists($path)) mkdir( $path , 0777 , true );

//echo "运行中，请耐心等待...<br/>";
        $info = "-- ----------------------------\r\n";
        $info .= "-- 日期：".date("Y-m-d H:i:s",time())."\r\n";
        $info .= "-- MySQL - 5.5.52-MariaDB : Database - ".$database."\r\n";
        $info .= "-- ----------------------------\r\n\r\n";
        $info .= "CREATE DATAbase IF NOT EXISTS `".$database."` DEFAULT CHARACTER SET utf8 ;\r\n\r\n";
        $info .= "USE `".$database."`;\r\n\r\n";

// 检查目录是否存在
        if(is_dir($path)){
// 检查目录是否可写
            if(is_writable($path)){
//echo '目录可写';exit;
            }else{
//echo '目录不可写';exit;
                chmod($path,0777);
            }
        }else{
//echo '目录不存在';exit;
// 新建目录
            mkdir($path, 0777, true);
//chmod($path,0777);
        }

// 检查文件是否存在
        $file_name = $path.$date.'.sql';
        $path_record = '/uploads/backup/'.$database.'/'.$date.'.sql';
        if(file_exists($file_name)){
            echo "数据备份文件已存在！";
            exit;
        }
        file_put_contents($file_name,$info,FILE_APPEND);

//查询数据库的所有表
        $result = Db::query('show tables');
//print_r($result);exit;

        foreach ($result as $k=>$v) {
//查询表结构
            $val = $v['Tables_in_'.$database];
            $sql_table = "show create table ".$val;
            $res = Db::query($sql_table);
//print_r($res);exit;
            $info_table = "-- ----------------------------\r\n";
            $info_table .= "-- Table structure for `".$val."`\r\n";
            $info_table .= "-- ----------------------------\r\n\r\n";
            $info_table .= "DROP TABLE IF EXISTS `".$val."`;\r\n\r\n";
            $info_table .= $res[0]['Create Table'].";\r\n\r\n";
//查询表数据
            $info_table .= "-- ----------------------------\r\n";
            $info_table .= "-- Data for the table `".$val."`\r\n";
            $info_table .= "-- ----------------------------\r\n\r\n";
            file_put_contents($file_name,$info_table,FILE_APPEND);
            $sql_data = "select * from ".$val;
            $data = Db::query($sql_data);
//print_r($data);exit;
            $count= count($data);
//print_r($count);exit;
            if($count<1) continue;
            foreach ($data as $key => $value){
                $sqlStr = "INSERT INTO `".$val."` VALUES (";
                foreach($value as $v_d){
                    $v_d = str_replace("'","\'",$v_d);
                    $sqlStr .= "'".$v_d."', ";
                }
//需要特别注意对数据的单引号进行转义处理
//去掉最后一个逗号和空格
                $sqlStr = substr($sqlStr,0,strlen($sqlStr)-2);
                $sqlStr .= ");\r\n";
                file_put_contents($file_name,$sqlStr,FILE_APPEND);
            }
            $info = "\r\n";
            file_put_contents($file_name,$info,FILE_APPEND);
        }
        $data = array(
            'admin_id'=>$this->admin_id,
            'path'=>$path_record,
            'create_time'=>time(),
        );
        Db::name('back_record')->insert($data);
        echo "数据备份完成！";
    }


    public function adminRole(){
        $roleList = Db::name('admin_role')->order('created DESC')->paginate(20);
        $page = $roleList->render();
        $roleArrList = $roleList->toArray();

        foreach ($roleArrList['data'] as $key=>$item) {
                $mp_power = json_decode($item['mp_power'],true);
                $MpList = Db::name('mp')->where('id','in',$mp_power)
                    ->field('name')->select();
                $mp_name = [];
                foreach ($MpList as $mp) {
                    $mp_name[] = $mp['name'];
                }
                $mp_name = implode(',',$mp_name);
                $roleArrList['data'][$key]['mp_name'] = $mp_name;

        }
        $this->assign('roleArrList', $roleArrList['data']);
        $this->assign('page', $page);
        return view('adminrole');

    }


    public function addAdminRole()
    {
        if (Request::isAjax()) {
            $_data = input();
            if(!$_data['role_name']) {
                ajaxMsg(0, '请输入角色名');
            }
            $mp_power = $_data['mp_power'];
            $mp_menu = $_data['mp_menu'];

            $role_name = trim($_data['role_name']);
            if (!$result = Db::name('admin_role')->where('role_name', 'eq', $role_name)
                ->find()) {

                $data['role_name'] = $role_name;
                if(is_array($mp_power)){
                    $mp_power = @json_encode(array_values($mp_power), true);
                }else{
                    $mp_power = [];
                }
                if(is_array($mp_menu)){
                    $mp_menu = @json_encode(array_values($mp_menu), true);
                }else{
                    $mp_menu = [];
                }
                $data['mp_power'] = $mp_power;
                $data['mp_menu'] = $mp_menu;
                $data['admin_id'] = $this->admin_id;
                $data['created'] = time();
                if (Db::name('admin_role')->insert($data)) {
                    ajaxMsg(1, '操作成功');
                } else {
                    ajaxMsg(0, '操作失败');
                }
            } else {
                ajaxMsg(0, '角色名已经存在');
            }
        } else {
            $MpList = Db::name('mp')
                ->select();
            foreach ($MpList as $key => $v) {
                $MpList[$key]['type_name'] = getMpType($v['type']);
            }

            $allMenu = Db::name('menu')->order('sort ASC')->select();
            $menuList = \Tree::makeTree($allMenu);

            $this->assign('menuList', $menuList);
            $this->assign('mpList', $MpList);
            return view('addadminrole');
        }

    }

    public function updateAdminRole($id){

        if (Request::isAjax()) {
            $_data = input();
            if(!$_data['role_name']) {
                ajaxMsg(0, '请输入角色名');
            }

            $mp_power = $_data['mp_power'];
            $mp_menu = $_data['mp_menu'];
            $role_name = trim($_data['role_name']);
            if (!$result = Db::name('admin_role')->where('role_name', 'eq', $role_name)->where('id', 'neq', $id)
                ->find()) {

                $data['role_name'] = $role_name;
                if(is_array($mp_power)){
                    $mp_power = @json_encode(array_values($mp_power), true);
                }else{
                    $mp_power = '';
                }
                if(is_array($mp_menu)){
                    $mp_menu = @json_encode(array_values($mp_menu), true);
                }else{
                    $mp_menu = [];
                }
                $data['mp_power'] = $mp_power;
                $data['mp_menu'] = $mp_menu;

               Db::name('admin_role')->where(['id' => $id])->update($data);
                    Cache::clear();
                    ajaxMsg(1, '操作成功');

            } else {
                ajaxMsg(0, '角色名已经存在');
            }
        } else {
            $MpList = Db::name('mp')
                ->select();
            $role = Db::name('admin_role')->where(['id' => $id])->find();
            $mp_power = $role['mp_power'] ? json_decode($role['mp_power'],true) : array();
            foreach ($MpList as $k=>$item) {
                $MpList[$k]['checked'] = 0;
                if(in_array($item['id'],$mp_power)){
                    $MpList[$k]['checked'] = 1;
                }
                $MpList[$k]['type_name'] = getMpType($item['type']);
            }
            $mp_menu = $role['mp_menu'] ? json_decode($role['mp_menu'],true) : array();
            $allMenu = Db::name('menu')->order('sort ASC')->select();
            foreach ($allMenu as $k=>$item) {
                $allMenu[$k]['checked'] = 0;
                if(in_array($item['id'],$mp_menu)){
                    $allMenu[$k]['checked'] = 1;
                }
            }
            $menuList = \Tree::makeTree($allMenu);

            $this->assign('menuList', $menuList);
            $this->assign('mpList', $MpList);
            $this->assign('role', $role);
            return view('updateadminrole');
        }


    }

    public function globalConfig($type = 1)
    {


        if (Request::isAjax()) {
            $_data = input();
            foreach ($_data as $k=>$datum) {
                if($k != 'type'){
                    if( Db::name('global_config')->where(['code' => $k,'admin_id'=>$this->admin_id])->find()){
                        Db::name('global_config')->where(['code' => $k,'admin_id'=>$this->admin_id])->update(['value' => $datum]);
                    }else{
                        $data = array(
                            'value'=>$datum,
                            'code'=>$k,
                            'admin_id'=>$this->admin_id
                        );
                        Db::name('global_config')->insert($data);
                    }
                }

            }
            ajaxMsg(1, '操作成功');

        } else {
            $configList = Db::name('global_config')->where(['admin_id'=>$this->admin_id])->select();
            $new_config = array();
            foreach ($configList as $item) {
                $new_config[$item['code']] = $item['value'];
            }
            $configs = getGlobalConfig($type);
            foreach ($configs as $k=>$item) {
                if(isset($new_config[$item['code']])){
                    $configs[$k]['value'] = $new_config[$item['code']];
                }
            }
            if($type == 2){
                $style_list = getTempletStyle();
                $this->assign('style_list',$style_list);
            }

            $this->assign('configList', $configs);
            $this->assign('intype',$type);
            return view('globalconfig');
        }
    }

}